<template>
    <div style="" class="qrCode" id="login_container">
    </div>
</template>


<script setup>
import {onMounted, toRefs } from "vue"
import {useStore} from 'vuex'
const store = useStore()


//扫码登录重新刷新的loading
// let redirectUrlLoading = ref(false) 
// 扫码登录后会掉地址
const redirectUrl = import.meta.env.VITE_APP_REDIRECT_URL
// 扫码登录跳转地址
let goto = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=&response_type=&scope=&state=&redirect_uri=${encodeURIComponent(redirectUrl)}`)
// 获取当前扫码登录后的url
let tmpAuthCode = window.location.search.split("&")[0].split("=")[1]

// 注册字组件通信
const emits = defineEmits(['upUrlLoading'])
// 修改扫码登录的loading显示
tmpAuthCode && emits('upUrlLoading', true)


// 这个钩子函数主要负责扫码登录的核心逻辑
onMounted(() => {
    // 生成钉钉扫码登录二维码
    DDLogin({
        id: "login_container", //这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
        goto: goto, //请参考注释里的方式
        style: "border:none;background-color:#FFFFFF;",
        width: "270",
        height: "370"
    })

    tmpAuthCode && emits('upUrlLoading', true)

    // 扫码登录后调用的函数
    let handleMessage = function (event) {
        let origin = event.origin
        console.log("origin", event.origin)
        if ( origin == "https://login.dingding.com" ) { //判断是否来自ddLogin扫码事件。
            let loginTmpCode = event.data
            // 对扫码后拿到的code追加跳转
            window.location.href = decodeURIComponent(goto + "&loginTmpCode=" + loginTmpCode)
        }
    }
    // 监听扫码登录的事件
    if (typeof window.addEventListener != 'undefined') {
        if (tmpAuthCode){
            store.dispatch('scanCodeLogin', {
                code: tmpAuthCode,
                state: 'auth'
            }).then(res => {
                console.log('成功', res)
                window.location.href = redirectUrl
            }, err => {
                console.log('失败', err)
            }) 
        }

        window.addEventListener('message', handleMessage, false)
    } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage)
    }
})
</script>


<style lang="scss" scoped>
.qrCode {
    width:270px;
    height:310px;
    background:#fff;
    border-radius:10px;
}
</style>